package com.woniu108.person.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu108.carService.commons.log.AdminHistoryLog;
import com.woniu108.carService.commos.dto.StoreDto;
import com.woniu108.carService.commos.exception.WoniuException;
import com.woniu108.carService.commos.model.Result;
import com.woniu108.carService.commos.util.JWTUtil;
import com.woniu108.carService.commos.util.RedisUtil;
import com.woniu108.carService.commos.util.StaticData;
import com.woniu108.person.client.EvaluateClient;
import com.woniu108.person.form.AddStoreForm;
import com.woniu108.person.form.StoreListForm;
import com.woniu108.person.model.Store;
import com.woniu108.person.model.StoreAdmin;
import com.woniu108.person.param.AddStoreParam;
import com.woniu108.person.param.StoreListParam;
import com.woniu108.person.service.StoreAdminService;
import com.woniu108.person.service.StoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 门店信息表 前端控制器
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/store")
@Api(tags = "门店信息接口")
public class StoreController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private StoreService storeService;
    @Resource
    private StoreAdminService storeAdminService;
    @Resource
    private EvaluateClient evaluateClient;
    public String getAdminId(String token){
        String refreshToken=redisUtil.getString(token);
        String adminId= JWTUtil.parseAdminToken(refreshToken).get("adminId").toString();
        return adminId;
    }

    /**
     *
     * @param form 新增门店信息
     * @param token
     * @return result 接口是否正常访问到结果
     */
    @PostMapping("/addStore.api")
    @ApiOperation("新增门店")
    @AdminHistoryLog
    public Result addStore(@RequestBody AddStoreForm form, @RequestHeader String token){
        String adminId = this.getAdminId(token);
        if(ObjectUtil.isEmpty(adminId)) throw new WoniuException("非管理员账户,不可操作新增",10001);
        AddStoreParam param= BeanUtil.toBean(form,AddStoreParam.class);
        param.setStoreState(StaticData.STORE_STATE_NORMAL);
        Store store=BeanUtil.toBean(param, Store.class);
        storeService.save(store);
        evaluateClient.createStoreScoreByStoreId(store.getStoreId());
        return Result.getResult().setMsg("新增门店成功");
    }

    /**
     * 根据门店编号查找门店信息(含门店负责人姓名，多个显示为json字符串形式)
     * @param storeId 门店ID
     * @return StoreDto 门店详细信息
     */
    @GetMapping("/getStoreById/{storeId}.c")
    @ApiOperation("根据门店编号查找门店信息")
    @ApiImplicitParam(name = "storeId",value ="门店ID" )
    public Result<StoreDto> getStoreById(@PathVariable("storeId") Integer storeId){
        Store store = storeService.getById(storeId);
        if(ObjectUtil.isEmpty(store)) throw new WoniuException("门店不存在",10001);
        if(store.getStoreState()!=StaticData.STORE_STATE_NORMAL) throw new WoniuException("门店状态异常",10001);
        StoreDto dto = BeanUtil.toBean(store, StoreDto.class);
        QueryWrapper<StoreAdmin> wrapper = new QueryWrapper<StoreAdmin>();
        wrapper.eq("store_id",storeId);
        wrapper.eq("store_admin_state",StaticData.ADMIN_STATE_NORMAL);
        List<StoreAdmin> list = storeAdminService.list(wrapper);
        if(ObjectUtil.isEmpty(list)) dto.setStoreAdminName("暂无门店负责人");
        String str = JSONUtil.toJsonStr(list);
        dto.setStoreName(str);
        return Result.getResult(StoreDto.class).setData(dto);
    }

    /**
     * 根据门店名称筛选门店列表
     * @param form 门店列表筛选信息 门店名称 每页数量 页码
     * @return  Page<StoreDto> 单页门店信息集合
     */
    @PostMapping("/storeList.api")
    @ApiOperation("根据门店名称筛选门店列表")
    public Result<Page<StoreDto>> storeList(@RequestBody StoreListForm form){
        StoreListParam param = BeanUtil.toBean(form, StoreListParam.class);
        String storeName = param.getStoreName();
        QueryWrapper<Store> wrapper = new QueryWrapper<>();
        if(storeName!=null) wrapper.like("store_name",storeName);
        wrapper.ne("store_state",StaticData.STORE_STATE_DELETE);
        List<Store> storeList = storeService.list(wrapper);
        List<StoreDto> dtos=new ArrayList<>();
        //获取dto
        for (Store store : storeList) {
            Integer storeId = store.getStoreId();
            StoreDto dto = BeanUtil.toBean(store, StoreDto.class);
            QueryWrapper<StoreAdmin> wrapper1 = new QueryWrapper<StoreAdmin>();
            wrapper1.eq("store_id",storeId);
            wrapper1.eq("store_admin_state",StaticData.ADMIN_STATE_NORMAL);
            StoreAdmin storeAdmin = storeAdminService.getOne(wrapper1);
            if(ObjectUtil.isEmpty(storeAdmin)){
                dto.setStoreAdminName("暂无门店负责人");
            }else{
                dto.setStoreAdminName(storeAdmin.getStoreAdminName());
            }
            dtos.add(dto);
        }
        //分页
        long total = dtos.size();
        long pages=total%param.getPageSize()==0?total/param.getPageSize():total/param.getPageSize()+1;
        Page<StoreDto> page=new Page<StoreDto>();
        List<StoreDto> dtosList=new ArrayList<>();
        int i=0;
        for (StoreDto dto : dtos) {
            if(i<param.getPageNum()*param.getPageSize().intValue()&&i>=(param.getPageNum()-1)*param.getPageSize().intValue()){
                dtosList.add(dto);
            }
            i=i+1;
        }
        page.setCurrent(param.getPageNum());
        page.setSize(param.getPageSize());
        page.setRecords(dtosList);
        page.setTotal(total);
        page.setPages(pages);
        return Result.newPageInstance(StoreDto.class).setData(page).setMsg("获取门店信息列表成功");
    }

    /**
     * 更换门店负责人
     * @param storeId 门店ID
     * @param storeAdminId 门店管理员ID
     * @return result 接口是否正常访问到结果
     */
    @GetMapping("/storeChargeAdminChange.api")
    @ApiOperation("更换门店负责人")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId",value ="门店ID" ),
            @ApiImplicitParam(name = "storeAdminId",value ="门店管理员ID" )
    })
    @AdminHistoryLog
    public Result storeChargeAdminChange(Integer storeId,String storeAdminId){
        StoreAdmin storeAdmin = storeAdminService.getById(storeAdminId);
        if(storeAdmin==null) throw new WoniuException("选择的门店管理员不存在",10001);
        if(storeAdmin.getStoreAdminState()!=StaticData.ADMIN_STATE_NORMAL) throw new WoniuException("门店管理员状态异常",10001);
        storeAdmin.setStoreId(storeId);
        Store store = storeService.getById(storeId);
        if(ObjectUtil.isEmpty(store)||store.getStoreState()==StaticData.STORE_STATE_DELETE) throw new WoniuException("门店不存在或状态异常",10001);
        storeAdminService.updateById(storeAdmin);
        return Result.getResult().setMsg("修改门店负责人成功");
    }

    /**
     * 门店地址修改
     * @param storeId 门店ID
     * @param storeAddress 门店地址
     * @return result 接口是否正常访问到结果
     */
    @GetMapping("/StoreChangeInfo.c")
    @ApiOperation("门店地址修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId",value ="门店ID" ),
            @ApiImplicitParam(name = "storeAddress",value ="门店地址" )
    })
    public Result storeChangeInfo(Integer storeId,String storeAddress){
        Store store = storeService.getById(storeId);
        if(ObjectUtil.isEmpty(store)||store.getStoreState()==StaticData.STORE_STATE_DELETE) throw new WoniuException("门店不存在或状态异常",10001);
        store.setStoreAddress(storeAddress);
        storeService.updateById(store);
        return Result.getResult().setMsg("门店地址修改成功");
    }

    /**
     * 修改门店状态
     * @param storeId 门店ID
     * @param changeType 修改状态名称
     * @return result 接口是否正常访问到结果
     */
    @GetMapping("/changeStoreState.c")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId",value ="门店ID" ),
            @ApiImplicitParam(name = "changeType",value ="修改状态名称" )
    })
    @ApiOperation("修改门店状态")
    public Result changeStoreState(Integer storeId,String changeType){
        Store store = storeService.getById(storeId);
        if(ObjectUtil.isEmpty(store)) throw new WoniuException("门店不存在",10001);
        Integer storeState=null;
        if("关闭".equals(changeType)) storeState=StaticData.STORE_STATE_DISABLED;
        if("删除".equals(changeType)) {
            storeState=StaticData.STORE_STATE_DELETE;
            evaluateClient.delStoreScore(storeId);
        }
        if("启用".equals(changeType)) storeState=StaticData.STORE_STATE_NORMAL;
        if(ObjectUtil.isEmpty(changeType)||storeState==null) throw new WoniuException("修改目标有误",10001);
        if(storeState==store.getStoreState()) throw new WoniuException("门店状态异常",10001);
        store.setStoreState(storeState);
        storeService.updateById(store);
        return Result.getResult().setMsg(changeType+"门店成功");
    }

}

